package com.hospital.controller;

import com.hospital.dao.DoctorDao;
import com.hospital.dao.DoctorViewDao;
import com.hospital.dao.impl.DoctorDaoImpl;
import com.hospital.dao.impl.DoctorViewDaoImpl;
import com.hospital.model.Doctor;
import com.hospital.model.DoctorView;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;

/**
 * 更新医生信息处理Servlet
 * 处理医生更新个人信息的请求，包括修改电话号码和密码
 */
@WebServlet("/updateDoctor")
public class UpdateDoctorServlet extends HttpServlet {
    /** 医生数据访问对象，用于处理医生基本信息的数据库操作 */
    private DoctorDao doctorDao=new DoctorDaoImpl();
    
    /** 医生视图数据访问对象，用于处理医生详细信息的查询 */
    private DoctorViewDao doctorViewDao=new DoctorViewDaoImpl();
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws  IOException {

        response.setContentType("application/json;charset=UTF-8");
        PrintWriter out = response.getWriter();

        try {
            // 获取表单数据
            String doctorId = ((DoctorView) request.getSession().getAttribute("doctor")).getDoctorId();
            String newPhone = request.getParameter("newPhone");
            String newPassword = request.getParameter("newPassword");
            String currentPassword = request.getParameter("currentPassword");
            // 验证当前密码
            Doctor doctor = doctorDao.findByDoctorId(doctorId);
            System.out.println(newPassword);
            if (!doctor.getDoctorPassword().equals(currentPassword)) {
                out.write("{\"success\":false,\"message\":\"当前密码错误！\"}");
                return;
            }

            // 更新信息
            boolean updated = doctorDao.updateDoctorInfo(doctorId, newPhone,
                    newPassword.isEmpty() ? currentPassword : newPassword);

            if (updated) {
                // 更新session中的医生信息
                DoctorView updatedDoctor = doctorViewDao.findByDoctorId(doctorId);
                request.getSession().setAttribute("doctor", updatedDoctor);
                out.write("{\"success\":true}");
            } else {
                out.write("{\"success\":false,\"message\":\"更新失败，请重试！\"}");
            }

        } catch (SQLException e) {
            e.printStackTrace();
            out.write("{\"success\":false,\"message\":\"系统错误，请稍后重试！\"}");
        }
    }
} 